package com.yq.cp.service.basics.impl;
import cn.afterturn.easypoi.entity.ImageEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.cp.config.UserThreadLocal;
import com.yq.cp.entity.basics.*;
import com.yq.cp.entity.basics.model.ExportExcelData;
import com.yq.cp.entity.basics.model.ExportWordData;
import com.yq.cp.entity.common.PageVo;
import com.yq.cp.entity.permission.User;
import com.yq.cp.entity.yw.YwZbgl;
import com.yq.cp.entity.yw.YwZbglGlry;
import com.yq.cp.entity.yw.YwZbglXq;
import com.yq.cp.mapper.basics.*;
import com.yq.cp.mapper.permission.UserMapper;
import com.yq.cp.mapper.yw.YwZbglGlryMapper;
import com.yq.cp.mapper.yw.YwZbglMapper;
import com.yq.cp.mapper.yw.YwZbglXqMapper;
import com.yq.cp.service.basics.InspectionTaskManagementService;
import com.yq.cp.utils.BeanCopyUtil;
import com.yq.cp.utils.DateTimeUtil;
import com.yq.cp.utils.ExcelUtil;
import com.yq.cp.utils.FileUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 巡检任务管理 服务实现类
 * </p>
 *
 * @author shenyuqing
 * @since 2024-08-27
 */
@Service
@EnableScheduling
public class InspectionTaskManagementServiceImpl extends ServiceImpl<InspectionTaskManagementMapper, InspectionTaskManagement> implements InspectionTaskManagementService {
    @Resource
    InspectionTaskManagementMapper inspectionTaskManagementMapper;
    @Resource
    InspectionItemManagementExtendMapper inspectionItemManagementExtendMapper;
    @Resource
    InspectionPointManagementMapper inspectionPointManagementMapper;
    @Resource
    PatrolPointMapper patrolPointMapper;
    @Resource
    InspectionPointManagementExtendMapper inspectionPointManagementExtendMapper;
    @Resource
    InspectionPointItemMapper inspectionPointItemMapper;
    @Resource
    InspectionItemManagementMapper inspectionItemManagementMapper;
    @Resource
    PersonnelRelationsMapper personnelRelationsMapper;
    @Resource
    PatrolPlanManagementMapper patrolPlanManagementMapper;
    @Resource
    YwZbglGlryMapper ywZbglGlryMapper;
    @Resource
    YwZbglMapper ywZbglMapper;
    @Resource
    YwZbglXqMapper ywZbglXqMapper;
    @Resource
    OrganizationalStructureMapper organizationalStructureMapper;
    @Resource
    PatrolRouteManagementMapper patrolRouteManagementMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    MessageMapper messageMapper;
    @Resource
    InspectionRoutePointMapper inspectionRoutePointMapper;
    @Resource
    PointInspectionItemsMapper pointInspectionItemsMapper;
    @Override
    public void exportWord(Long id, HttpServletResponse response){
        InspectionTaskManagement byId = inspectionTaskManagementMapper.selectById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("siteName",byId.getSiteName());
        map.put("task",byId.getPlanName());
        map.put("route",byId.getRouteName());
        String strDateTime1 = null;
        if (!Objects.isNull(byId.getTimes())){
            strDateTime1 = DateTimeUtil.getStrDateTime(byId.getTimes());}
        map.put("time",strDateTime1);
        map.put("admin",byId.getHeadName());
        List<PersonnelRelations> list1 = personnelRelationsMapper.selectList(new QueryWrapper<PersonnelRelations>()
                .eq("other_id", byId.getId()));
        List<Long> collect1 = list1.stream().map(PersonnelRelations::getUserId).collect(Collectors.toList());
        List<User> users = userMapper.selectBatchIds(collect1);
        String str = "";
        for (User user : users) {
            str = str+" "+user.getNickname();
        }

        map.put("dutynames",str);
        map.put("receivingname",byId.getReceivingname());
        String strDateTime = DateTimeUtil.getStrDateTime(byId.getReceivingtime());
        map.put("receivingtime",strDateTime);
        List<InspectionPointManagementExtend> extendList = inspectionPointManagementExtendMapper.selectList(new QueryWrapper<InspectionPointManagementExtend>()
                .eq("plan_id", byId.getId()));
        List<Long> collect = extendList.stream().map(InspectionPointManagementExtend::getId).collect(Collectors.toList());
        List<InspectionItemManagementExtend> taskId = inspectionItemManagementExtendMapper.selectList(new QueryWrapper<InspectionItemManagementExtend>()
                .in("point_id", collect));
        int order = 1;
        List<ExportWordData> list = new ArrayList<>();
        for (InspectionItemManagementExtend extend : taskId) {
            ExportWordData data = new ExportWordData();
            data.setOrder(order);
            InspectionPointManagementExtend pointManagement = inspectionPointManagementExtendMapper.selectById(extend.getPointId());
            data.setX1(pointManagement.getName());
            data.setX2(extend.getName());
            data.setX3(extend.getValidationCriteria());
            data.setX4(extend.getMethod());
            data.setX5(extend.getTool());
            data.setX6(extend.getResult());
            if (extend.getState()==0)
                data.setX7("正常");
            else
                data.setX7("异常");
            ImageEntity simage = new ImageEntity();
            simage.setHeight(50);
            simage.setWidth(50);
            simage.setUrl(extend.getPhoto());
            //将simage对象的类型设置为URL类型。
            //该图像实体表示的是一个通过URL链接获取的远程图像，而不是一个本地存储的图像。
            simage.setType(ImageEntity.URL);
            data.setX8(simage);
            list.add(data);
            order++;
        }
        map.put("list",list);
        FileUtils.exportWordByModel(response,map,"templates/word.docx","计划");
    }

    @Override
    public void exportExcel(PageVo vo) {
        QueryWrapper<InspectionTaskManagement> wrapper = new QueryWrapper<>();
        if (!Objects.isNull(vo.getLike())&&!"".equals(vo.getLike()))
            wrapper.like("planName",vo.getLike());
        if (!Objects.isNull(vo.getState()))
            wrapper.eq("state",vo.getState());
        List<InspectionTaskManagement> list = inspectionTaskManagementMapper.selectList(wrapper);
        list.stream().forEach(inspectionTaskManagement -> {
            if (inspectionTaskManagement.getState()==0)
                inspectionTaskManagement.setStateName("待执行");
            else
                inspectionTaskManagement.setStateName("已执行");
        });
        List<ExportExcelData> data = new ArrayList<>();
        for (InspectionTaskManagement taskManagement : list) {
            ExportExcelData exportExcelData = new ExportExcelData();
            exportExcelData.setPlanName(taskManagement.getPlanName());
            exportExcelData.setCreateName(taskManagement.getCreateName());
            exportExcelData.setStateName(taskManagement.getStateName());
            exportExcelData.setSiteName(taskManagement.getSiteName());
            exportExcelData.setCreateTime(DateTimeUtil.getStrDateTime(taskManagement.getCreateTime()));
            data.add(exportExcelData);
        }
        //List<ExportExcelData> data = BeanCopyUtil.copyList(list, ExportExcelData.class);
        ExcelUtil.doWrite("巡检任务列表",null,ExportExcelData.class,data);
    }

//    @Override
//    public InspectionTaskManagement detail(InspectionTaskManagement vo) {
//        InspectionTaskManagement taskManagement = inspectionTaskManagementMapper.selectById(vo);
//        List<InspectionItemManagementExtend> taskId = inspectionItemManagementExtendMapper.selectList(new QueryWrapper<InspectionItemManagementExtend>()
//                .eq("task_id", taskManagement.getId()));
//        taskManagement.setItemExtendList(taskId);
//        return taskManagement;
//    }

    @Override
    public void realAdd(InspectionTaskManagement vo) {
        vo.setCreateName(UserThreadLocal.get().getUsername());
        vo.setState(0);
        PatrolRouteManagement patrolRouteManagement = patrolRouteManagementMapper.selectById(vo.getRouteId());
        vo.setRouteName(patrolRouteManagement.getName());
        OrganizationalStructure structure = organizationalStructureMapper.selectById(vo.getSiteId());
        vo.setSiteName(structure.getName());
        User user = userMapper.selectById(vo.getHeadId());
        vo.setHeadName(user.getNickname());
        inspectionTaskManagementMapper.insert(vo);
        List<InspectionRoutePoint> patrolPoints1 = inspectionRoutePointMapper.selectList(new QueryWrapper<InspectionRoutePoint>()
                .eq("route_id", vo.getRouteId()));
        List<Long> collect = patrolPoints1.stream().map(InspectionRoutePoint::getPointId).collect(Collectors.toList());
        List<InspectionPointManagement> patrolPoints = inspectionPointManagementMapper.selectBatchIds(collect);
        for (InspectionPointManagement patrolPoint : patrolPoints) {
            InspectionPointManagementExtend inspectionPointManagementExtend = new InspectionPointManagementExtend();
            inspectionPointManagementExtend.setName(patrolPoint.getName());
            inspectionPointManagementExtend.setPlanId(vo.getId());
            inspectionPointManagementExtend.setState(0);
            inspectionPointManagementExtend.setType(patrolPoint.getType());
            inspectionPointManagementExtend.setAssociatedDevicesId(patrolPoint.getId());
            inspectionPointManagementExtendMapper.insert(inspectionPointManagementExtend);
            List<InspectionPointItem> items = inspectionPointItemMapper.selectList(new QueryWrapper<InspectionPointItem>()
                    .eq("route_id", vo.getRouteId()));
            if (!items.isEmpty()) {
                for (InspectionPointItem item : items) {
                    InspectionRoutePoint inspectionRoutePoint = inspectionRoutePointMapper.selectOne(new QueryWrapper<InspectionRoutePoint>()
                            .eq("point_id", patrolPoint.getId()).eq("route_id", vo.getRouteId()));
                    InspectionItemManagement inspectionItemManagement = inspectionItemManagementMapper.selectById(item.getItemId());
                    if (item.getRoutePointId().equals(inspectionRoutePoint.getId())) {
                        InspectionItemManagementExtend extend = BeanCopyUtil.copyObject(inspectionItemManagement, InspectionItemManagementExtend.class);
                        extend.setPointId(inspectionPointManagementExtend.getId());
                        extend.setId(null);
                        inspectionItemManagementExtendMapper.insert(extend);
                    }
                }
            }if (patrolPoint.getType()==3){
                InspectionItemManagementExtend extend = new InspectionItemManagementExtend();
                extend.setPointId(inspectionPointManagementExtend.getId());
                extend.setName(patrolPoint.getName());
                inspectionItemManagementExtendMapper.insert(extend);
            }
        }
//        List<InspectionPointManagementExtend> extendList = BeanCopyUtil.copyList(patrolPoints, InspectionPointManagementExtend.class);
//        extendList.stream().forEach(extend -> extend.setId(null));
//        extendList.stream().forEach(extend -> extend.setPlanId(vo.getId()));
//        extendList.stream().forEach(extend -> inspectionPointManagementExtendMapper.insert(extend));
//        List<InspectionPointItem> items = inspectionPointItemMapper.selectList(new QueryWrapper<InspectionPointItem>()
//                .eq("route_id", vo.getRouteId()));
//        List<InspectionItemManagement> inspectionItemManagements = inspectionItemManagementMapper
//                .selectBatchIds(items.stream().map(InspectionPointItem::getItemId).collect(Collectors.toList()));
//        List<InspectionItemManagementExtend> anExtends = BeanCopyUtil.copyList(inspectionItemManagements, InspectionItemManagementExtend.class);
//        anExtends.stream().forEach(inspectionItemManagementExtend -> inspectionItemManagementExtend.setId(null));
//        anExtends.stream().forEach(extend -> inspectionItemManagementExtendMapper.insert(extend));
        for (Long userId : vo.getUserIds()) {
            PersonnelRelations person =  new PersonnelRelations();
            person.setUserId(userId);
            person.setOtherId(vo.getId());
            personnelRelationsMapper.insert(person);
            Message message = new Message();
            message.setType(2);
            message.setUserId(userId);
            message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
            message.setIsReceive(0);
            messageMapper.insert(message);
        }
    }
    @Scheduled(fixedRate = 500000)
    public void scheduled() throws ParseException {
        // 获取当前时间
        Date date = DateTimeUtil.dqsj();
        // 创建一个日历实例
        Calendar calendar = Calendar.getInstance();
        // 将当前时间设置为日历的时间
        calendar.setTime(date);
        // 获取当前日期是一星期中的第几天（星期日为1，星期一为2，以此类推）
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        List<PatrolPlanManagement> plans = patrolPlanManagementMapper.selectList(new QueryWrapper<>());

        if (!plans.isEmpty()){
            for (PatrolPlanManagement plan : plans) {
                OrganizationalStructure structure = organizationalStructureMapper.selectById(plan.getSiteId());
                if (Objects.isNull(structure))
                    continue;
                QueryWrapper<YwZbgl> ywZbglWrapper = new QueryWrapper<>();
                if (dayOfWeek==1)
                    ywZbglWrapper.eq("zj",0);
                else
                    ywZbglWrapper.eq("zj",dayOfWeek-1);
                ywZbglWrapper.eq("nyz_id",plan.getSiteId());
                YwZbgl ywZbgl = ywZbglMapper.selectOne(ywZbglWrapper);
                if (Objects.isNull(ywZbgl))
                    continue;
                List<YwZbglXq> zbglId = ywZbglXqMapper.selectList(new QueryWrapper<YwZbglXq>()
                        .eq("zbgl_id", ywZbgl.getId()));
                List<Long> collect = zbglId.stream().map(YwZbglXq::getId).collect(Collectors.toList());
                List<YwZbglGlry> glId = ywZbglGlryMapper.selectList(new QueryWrapper<YwZbglGlry>().in("gl_id", collect));
                List<Long> userIds = glId.stream().map(YwZbglGlry::getUserId).collect(Collectors.toList());
                //YwZbglGlry fzId = ywZbglGlryMapper.selectOne(new QueryWrapper<YwZbglGlry>().eq("type",1).in("gl_id", collect));

                if (userIds.isEmpty())
                    break;
                List<InspectionTaskManagement> planId = inspectionTaskManagementMapper.selectList(new QueryWrapper<InspectionTaskManagement>()
                        .eq("plan_id", plan.getId()).orderByDesc("create_time"));
                if (planId.isEmpty()){
                    if (plan.getMonthOrWeek()==0){
                        if (Integer.parseInt(plan.getDayOrWeek())==-1){
                            //insertTask(plan,userIds,fzId.getUserId());
                            insertTask(plan,userIds,1L);
                            for (Long userId : userIds) {
                                Message message = new Message();
                                message.setType(2);
                                message.setUserId(userId);
                                message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                            continue;
                        }


                        LocalDate today = LocalDate.now(); // 获取当前日期
                        int dayOfMonth = today.getDayOfMonth(); // 获取当前日期是本月的第几天
                        if (Integer.parseInt(plan.getDayOrWeek())==dayOfMonth){
                            //insertTask(plan,userIds,fzId.getUserId());
                            insertTask(plan,userIds,1L);
                            for (Long userId : userIds) {
                                Message message = new Message();
                                message.setType(2);
                                message.setUserId(userId);
                                message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                        }
                    }else if (plan.getMonthOrWeek()==1){
                        if (Integer.parseInt(plan.getDayOrWeek())==-1){
                            //insertTask(plan,userIds,fzId.getUserId());
                            insertTask(plan,userIds,1L);
                            for (Long userId : userIds) {
                                Message message = new Message();
                                message.setType(2);
                                message.setUserId(userId);
                                message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                            continue;
                        }

                        if (dayOfWeek==1&&Integer.parseInt(plan.getDayOrWeek())==7){
                            //insertTask(plan,userIds,fzId.getUserId());
                            insertTask(plan,userIds,1L);
                            for (Long userId : userIds) {
                                Message message = new Message();
                                message.setType(2);
                                message.setUserId(userId);
                                message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                        }
                        if (Integer.parseInt(plan.getDayOrWeek())==dayOfWeek-1){
                            //insertTask(plan,userIds,fzId.getUserId());
                            insertTask(plan,userIds,1L);
                            for (Long userId : userIds) {
                                Message message = new Message();
                                message.setType(2);
                                message.setUserId(userId);
                                message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                        }
                    }else {
                        insertTask(plan,userIds,1L);
                        for (Long userId : userIds) {
                            Message message = new Message();
                            message.setType(2);
                            message.setUserId(userId);
                            message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                            message.setIsReceive(0);
                            messageMapper.insert(message);
                        }

                    }
                }else {
                    InspectionTaskManagement taskManagement = planId.get(0);
                    if (plan.getMonthOrWeek()==0){
                        if (Integer.parseInt(plan.getDayOrWeek())==-1){
                            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMM");
                            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                            String format = sdf.format(new Date());

                            SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMM");
                            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                            String format1 = sdf1.format(taskManagement.getCreateTime());
                            if (Integer.parseInt(format)>Integer.parseInt(format1)){
                                insertTask(plan,userIds,1L);
                                for (Long userId : userIds) {
                                    Message message = new Message();
                                    message.setType(2);
                                    message.setUserId(userId);
                                    message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                    message.setIsReceive(0);
                                    messageMapper.insert(message);
                                }
                            }
                            continue;
                        }
                        LocalDate today = LocalDate.now(); // 获取当前日期
                        int dayOfMonth = today.getDayOfMonth(); // 获取当前日期是本月的第几天
                        Calendar calendar1 = Calendar.getInstance(); // 获取当前时间的Calendar对象

                        int currentMonth = calendar1.get(Calendar.MONTH); // 获取当前月份
                        calendar1.set(Calendar.MONTH, currentMonth + Integer.parseInt(plan.getDayOrWeek())); // 将月份增加对应的个月
                        Date time = calendar1.getTime();
                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String strDateTime = DateTimeUtil.getStrDateTime(taskManagement.getCreateTime());
                        Date date1=getMonthDate(sdf.parse(strDateTime),plan.getNumber());
                        if (date1.getTime()<=DateTimeUtil.dqsj().getTime()&&Integer.parseInt(plan.getDayOrWeek())==dayOfMonth){
                            //insertTask(plan,userIds,fzId.getUserId());
                            insertTask(plan,userIds,1L);
                            for (Long userId : userIds) {
                                Message message = new Message();
                                message.setType(2);
                                message.setUserId(userId);
                                message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                        }
                    }else if (plan.getMonthOrWeek()==1){
                        if (Integer.parseInt(plan.getDayOrWeek())==-1){
                            // 假设给定的日期
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            String[] parts = sdf.format(taskManagement.getCreateTime()).split("-");
                            int year = Integer.parseInt(parts[0]);
                            int month = Integer.parseInt(parts[1]);
                            int day = Integer.parseInt(parts[2]);


                            LocalDate givenDate = LocalDate.of(year, month, day);
                            //int value = givenDate.getDayOfWeek().getValue();
                            LocalDate nextMonday = givenDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
                            ZoneId zone = ZoneId.systemDefault();
                            Instant instant = nextMonday.atStartOfDay().atZone(zone).toInstant();
                            Date da = Date.from(instant);
                            if (da.getTime()<=DateTimeUtil.dqsj().getTime()){
                                insertTask(plan,userIds,1L);
                                for (Long userId : userIds) {
                                    Message message = new Message();
                                    message.setType(2);
                                    message.setUserId(userId);
                                    message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                    message.setIsReceive(0);
                                    messageMapper.insert(message);
                                }
                            }
                            continue;
                        }
                        long time = taskManagement.getCreateTime().getTime();
                        long i = plan.getNumber() * 7 * 86400000;
                        Date date1 = new Date(time + i);

                        if (date1.getTime()<=DateTimeUtil.dqsj().getTime()&&dayOfWeek==1&&Integer.parseInt(plan.getDayOrWeek())==7) {
                            //insertTask(plan, userIds, fzId.getUserId());
                            insertTask(plan,userIds,1L);
                            for (Long userId : userIds) {
                                Message message = new Message();
                                message.setType(2);
                                message.setUserId(userId);
                                message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                        }
                        if (date1.getTime()<=DateTimeUtil.dqsj().getTime()&&Integer.parseInt(plan.getDayOrWeek())==dayOfWeek-1) {
                            //insertTask(plan, userIds, fzId.getUserId());
                            insertTask(plan,userIds,1L);
                            for (Long userId : userIds) {
                                Message message = new Message();
                                message.setType(2);
                                message.setUserId(userId);
                                message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                        }
                    }else {
                        long time = taskManagement.getCreateTime().getTime();
                        long i =  86400000;
                        Date date1 = new Date(time + i);
                        if (date1.getTime()<=DateTimeUtil.dqsj().getTime()){
                            insertTask(plan,userIds,1L);
                            for (Long userId : userIds) {
                                Message message = new Message();
                                message.setType(2);
                                message.setUserId(userId);
                                message.setTitle("尊敬的用户，有新的巡检信息已生成，请尽快受理并处理！！！");
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                        }

                    }

                }
            }

        }

    }

    public static Date getMonthDate(Date startDate,int month){
        LocalDateTime localDateTime = startDate.toInstant()
                .atZone(ZoneId.systemDefault() )
                .toLocalDateTime().plusMonths(month);
        Date date = Date.from(localDateTime.atZone( ZoneId.systemDefault()).toInstant());
        return date;
    }


    //定时计划添加任务
    private void insertTask(PatrolPlanManagement plan,List<Long> userIds,Long fzid){
        InspectionTaskManagement vo = new InspectionTaskManagement();
        vo.setRouteId(plan.getRouteId());
        vo.setSiteId(plan.getSiteId());
        OrganizationalStructure structure = organizationalStructureMapper.selectById(plan.getSiteId());
        vo.setSiteName(structure.getName());
        vo.setPlanName(plan.getName());
        vo.setPlanId(plan.getId());
//        vo.setHeadId(fzid);
//        User user = userMapper.selectById(fzid);
//        vo.setHeadName(user.getNickname());
        PatrolRouteManagement patrolRouteManagement = patrolRouteManagementMapper.selectById(vo.getRouteId());
        vo.setRouteName(patrolRouteManagement.getName());
        vo.setState(0);
        vo.setCreateName(patrolRouteManagement.getCreateName());
        inspectionTaskManagementMapper.insert(vo);

        List<InspectionRoutePoint> patrolPoints1 = inspectionRoutePointMapper.selectList(new QueryWrapper<InspectionRoutePoint>()
                .eq("route_id", vo.getRouteId()));
        List<Long> collect = patrolPoints1.stream().map(InspectionRoutePoint::getPointId).collect(Collectors.toList());
        List<InspectionPointManagement> patrolPoints = inspectionPointManagementMapper.selectBatchIds(collect);
        for (InspectionPointManagement patrolPoint : patrolPoints) {
            InspectionPointManagementExtend inspectionPointManagementExtend = new InspectionPointManagementExtend();
            inspectionPointManagementExtend.setName(patrolPoint.getName());
            inspectionPointManagementExtend.setPlanId(vo.getId());
            inspectionPointManagementExtend.setState(0);
            inspectionPointManagementExtend.setType(patrolPoint.getType());
            inspectionPointManagementExtend.setAssociatedDevicesId(patrolPoint.getId());
            inspectionPointManagementExtendMapper.insert(inspectionPointManagementExtend);
            List<InspectionPointItem> items = inspectionPointItemMapper.selectList(new QueryWrapper<InspectionPointItem>()
                    .eq("route_id", vo.getRouteId()));
            if (!items.isEmpty()) {
                for (InspectionPointItem item : items) {
                    InspectionRoutePoint inspectionRoutePoint = inspectionRoutePointMapper.selectOne(new QueryWrapper<InspectionRoutePoint>()
                            .eq("point_id", patrolPoint.getId()).eq("route_id", vo.getRouteId()));
                    InspectionItemManagement inspectionItemManagement = inspectionItemManagementMapper.selectById(item.getItemId());
                    if (item.getRoutePointId().equals(inspectionRoutePoint.getId())) {
                        InspectionItemManagementExtend extend = BeanCopyUtil.copyObject(inspectionItemManagement, InspectionItemManagementExtend.class);
                        extend.setPointId(inspectionPointManagementExtend.getId());
                        extend.setId(null);
                        inspectionItemManagementExtendMapper.insert(extend);
                    }
                }
            }
            if (patrolPoint.getType()==3) {
                InspectionItemManagementExtend extend = new InspectionItemManagementExtend();
                extend.setPointId(inspectionPointManagementExtend.getId());
                extend.setName(patrolPoint.getName());
                inspectionItemManagementExtendMapper.insert(extend);
            }
        }

        for (Long userId : userIds) {
            PersonnelRelations person =  new PersonnelRelations();
            person.setUserId(userId);
            person.setOtherId(vo.getId());
            personnelRelationsMapper.insert(person);
        }

    }

}
